package ming.listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.HashMap;
import java.util.Map;



@WebListener
public class Mylistener implements HttpSessionListener {
    private static Map sessionMap = new HashMap();

    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        boolean flag = true;
        System.out.println("sessionCreated.SessionId()"+httpSessionEvent.getSession().getId());
//        System.out.println("sessionCreated.getSession()"+httpSessionEvent.getSession());
        for(Object key : sessionMap.keySet()) {
            if(key == httpSessionEvent.getSession().getId()) {
                flag = false;
                break;
            }
        }
        if(flag) {
            sessionMap.put(httpSessionEvent.getSession().getId(), httpSessionEvent.getSession());
        }
        ServletContext ctx = httpSessionEvent.getSession().getServletContext();

        ctx.setAttribute("numSessions", sessionMap.size());
        System.out.println("sessionMap.size()"+sessionMap.size());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        boolean flag = false;
        System.out.println("sessionDestroyed.SessionId()"+httpSessionEvent.getSession().getId());
//        System.out.println("sessionDestroyed.getSession()"+httpSessionEvent.getSession());
        for(Object key : sessionMap.keySet()) {
            if(key == httpSessionEvent.getSession().getId()) {
                flag = true;
                break;
            }
        }
        if(flag) {
            sessionMap.remove(httpSessionEvent.getSession().getId());
        }
        ServletContext ctx = httpSessionEvent.getSession().getServletContext();
        ctx.setAttribute("numSessions", sessionMap.size());
        System.out.println("sessionMap.size()"+sessionMap.size());

    }
}


